package com.wyp.design.pattern.creational.singleton.Eunm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

/**
 * @author: yipeng.wang01@hand-china.com-25490
 * @TIME: 2020/2/15/20:35
 **/
public enum EnumSingleton {
    INSTANCE{
        @Override
        public  void print(){
            System.out.println("enum!");
        }
    };

    public abstract  void print();
    private Object data;

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static EnumSingleton getInstance() {
        return INSTANCE;
    }

    public static void main(String[] args) throws Exception {
        //序列化和反序列化不对枚举类型做任何破坏
        EnumSingleton instance = EnumSingleton.getInstance();

        //测试枚举类型中对象是否发生变化
        instance.setData(new Object());
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("enum_file"));
        oos.writeObject(instance);


        File file = new File("enum_file");
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
        EnumSingleton newInstance = (EnumSingleton) ois.readObject();

//        System.out.println(newInstance.getData());
//        System.out.println(instance.getData());
//        System.out.println(newInstance.getData() == instance.getData());


        //测试反射对枚举单例模式的破坏
        Class<EnumSingleton> innerClassClass = EnumSingleton.class;
        //获取私有构造器
//        Constructor<EnumSingleton> constructor = innerClassClass.getDeclaredConstructor(String.class,int.class);
//        constructor.setAccessible(true);
//        EnumSingleton newInstance2 = constructor.newInstance("wyp",1);
//        EnumSingleton instance2 = EnumSingleton.getInstance();
//
//        System.out.println(newInstance2);
//        System.out.println(instance2);
//        System.out.println(newInstance2 == instance2);

        //调用枚举中的方法
        newInstance.print();

    }
}
